package edu.xhu.video.service.impl;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.xhu.common.exception.CustomException;
import edu.xhu.model.biliuser.dtos.RatioDto;
import edu.xhu.model.biliuser.pojos.BiliUser;
import edu.xhu.model.common.dtos.ResponseResult;
import edu.xhu.model.common.enums.AppHttpCodeEnum;
import edu.xhu.model.video.pojos.BiliVideoData;
import edu.xhu.video.mapper.BiliVideoDataMapper;
import edu.xhu.video.mapper.BiliVideoMapper;
import edu.xhu.video.service.BiliVideoService;
import edu.xhu.model.video.pojos.BiliVideo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import edu.xhu.api.user.UserClient;
import java.util.HashMap;
import java.util.Map;


@Service
@RequiredArgsConstructor
@Slf4j
public class BiliVideoServiceImpl extends ServiceImpl<BiliVideoMapper, BiliVideo> implements BiliVideoService {

    private final BiliVideoMapper biliVideoMapper;

    private final BiliVideoDataMapper biliVideoDataMapper;

    private final UserClient userClient;
    /**
     * b站视频上传
     * @param vid
     * @return
     */
    /*TODO 分布式事务*/
    @Transactional
    @Override
    public ResponseResult<?> getVideoDetail(Long vid) {
        Map<String, Object> resultMap = new HashMap<>(); //最终的结果集
        BiliVideo biliVideo = biliVideoMapper.selectById(vid);
        if(biliVideo == null){
            return ResponseResult.errorResult(500,"视频不存在");
        }
        resultMap.put("biliVideo",biliVideo);
        BiliVideoData biliVideoData = biliVideoDataMapper.selectById(vid);
        if(biliVideoData == null){
            return ResponseResult.errorResult(500,"视频数据不存在");
        }
        resultMap.put("biliVideoData",biliVideoData);
        ResponseResult<?> oneUserById = userClient.getOneUserById(biliVideo.getUserId());
        if (!oneUserById.getCode().equals(200)) {
            return ResponseResult.errorResult(500,"用户数据不存在");
        }
        BiliUser biliUser = JSONUtil.toBean(oneUserById.getData().toString(), BiliUser.class);
        resultMap.put("user",biliUser);
        return ResponseResult.okResult(resultMap);
    }
}
